const mongoose = require('mongoose');

const formSchema = new mongoose.Schema({
  projectId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Project',
    index: true
  },
  sectionId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Section',
    required: false  // 改为可选，支持独立表单
  },
  // projectId 字段已移除，支持多对多关系
  name: {
    type: String,
    required: true,
    trim: true,
    maxlength: 200
  },
  code: {
    type: String,
    required: false,
    trim: true
  },
  order: {
    type: Number,
    required: true
  },
  description: {
    type: String,
    trim: true,
    maxlength: 1000
  },
  type: {
    type: String,
    enum: ['form', 'template'],
    default: 'form'
  },
  isTemplate: {
    type: Boolean,
    default: true  // 默认为模板表单
  },
  config: {
    fields: {
      type: [mongoose.Schema.Types.Mixed],
      default: []
    },
    lastUpdated: Date,
    formConfig: {
      layout: {
        type: String,
        enum: ['grid', 'flex', 'table'],
        default: 'grid'
      },
      theme: {
        type: String,
        enum: ['default', 'compact', 'detailed'],
        default: 'default'
      },
      validation: {
        enabled: {
          type: Boolean,
          default: true
        },
        rules: mongoose.Schema.Types.Mixed
      }
    }
  }
}, {
  timestamps: { createdAt: 'createTime', updatedAt: 'updateTime' }
});

// 表单编码在同项目内唯一（仅当提供且非空时才参与唯一约束）
// 复合索引：同一项目内编码唯一，允许多个空值
formSchema.index(
  { projectId: 1, code: 1 },
  { 
    unique: true, 
    sparse: true, 
    partialFilterExpression: { 
      code: { $type: 'string', $ne: '', $exists: true } 
    } 
  }
);
// 添加模板标识索引
formSchema.index({ isTemplate: 1 });

// 其他索引
formSchema.index({ sectionId: 1, order: 1 });
formSchema.index({ 'config.fields.type': 1 });
formSchema.index({ sectionId: 1, isTemplate: 1 });

module.exports = mongoose.model('Form', formSchema);